package com.gitee.magic.context.editor;

import java.util.HashMap;
import java.util.Map;

import com.gitee.magic.context.PropertyConverterEditor;
import com.gitee.magic.core.converter.AbstractConverterEditor;
import com.gitee.magic.core.json.JsonObject;

/**
 * @author start
 */
public class MapConverterEditor extends AbstractConverterEditor<JsonObject> {

	private AbstractConverterEditor<?> kEditor;
	private AbstractConverterEditor<?> vEditor;
	
	public MapConverterEditor(Class<?> kPrototype,Class<?> vPrototype) {
		super(kPrototype);
		kEditor=PropertyConverterEditor.getBasicConverter(kPrototype);
		vEditor=PropertyConverterEditor.getBasicConverter(vPrototype);
	}

	@Override
	public void restore(Object value) {
		if (value != null) {
			JsonObject json=(JsonObject)value;
			setSource(json);
			Map<Object,Object> content=new HashMap<>(100);
			for(String key:json.keySet()) {
				Object val=json.get(key);
				Object kk=null;
				if(kEditor==null) {
					kk=key;
				}else {
					kEditor.setValue(key);
					kk=kEditor.getSource();
				}
				Object vv=null;
				if(vEditor==null) {
					vv=val;
				}else {
					vEditor.setValue(val);
					vv=vEditor.getSource();
				}
				content.put(kk,vv);
			}
			setValue(content);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public JsonObject converter() {
		if (getValue() == null) {
			return null;
		}
		Map<Object,Object> content = (Map<Object,Object>) getValue();
		JsonObject jsons = new JsonObject();
		for(Object key:content.keySet()) {
			Object val=content.get(key);
			Object kk=null;
			if(kEditor==null) {
				kk=key;
			}else {
				kEditor.setValue(key);
				kk=kEditor.getSource();
			}
			Object vv=null;
			if(vEditor==null) {
				vv=val;
			}else {
				vEditor.setValue(val);
				vv=vEditor.getSource();
			}
			jsons.put(String.valueOf(kk), vv);
		}
		return jsons;
	}

	@Override
	public Object getSource() {
		return converter();
	}

}
